//
//  KCMainViewController.m
//  MapKit Annotation
//
//  Created by Kenshin Cui on 14/3/27.
//  Copyright (c) 2014年 Kenshin Cui. All rights reserved.
//  37.785834   -122.406417
//  39.92 116.39

#import "KCMainViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "KCAnnotation.h"
#import "KCCalloutAnnotationView.h"
#import "KCCalloutAnnotation.h"

//CLLocationManagerDelegate

@interface KCMainViewController ()<MKMapViewDelegate>{
    //CLLocationManager 切记定义成成员变量、或者属性，否则导致不弹出系统提示打开定位提示框
    CLLocationManager *_locationManager;
    MKMapView *_mapView;
    CLLocationCoordinate2D coordinate;
}
@property(nonatomic,strong) CLGeocoder *geocoder;
@property(nonatomic,retain)UIButton *button;
@end

@implementation KCMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initGUI];
}

#pragma mark 添加地图控件
-(void)initGUI{
    CGRect rect=[UIScreen mainScreen].bounds;
    _mapView=[[MKMapView alloc]initWithFrame:rect];
    [self.view addSubview:_mapView];
    _mapView.delegate=self;
    
//    //请求定位服务(在info中配置NSLocationWhenInUseUsageDescription)
//    _locationManager=[[CLLocationManager alloc]init];
//    if(![CLLocationManager locationServicesEnabled]||[CLLocationManager authorizationStatus]!=kCLAuthorizationStatusAuthorizedWhenInUse){
//        [_locationManager requestWhenInUseAuthorization];
//    }
//    else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
//        //设置代理
//        _locationManager.delegate=self;
//        //设置定位精度
//        _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//        //定位频率,每隔多少米定位一次
//        CLLocationDistance distance=10.0;//十米定位一次
//        _locationManager.distanceFilter=distance;
//        //启动跟踪定位
//        [_locationManager startUpdatingLocation];
//    }
    
    //用户位置追踪(用户位置追踪用于标记用户当前位置，此时会调用定位服务)
    _mapView.userTrackingMode=MKUserTrackingModeFollow;
    
    //设置地图类型
    _mapView.mapType=MKMapTypeStandard;
    
    
    //添加大头针
    [self addAnnotation];
    
    self.button=[UIButton buttonWithType:UIButtonTypeCustom];
    _button.frame=CGRectMake(10, 70, 30, 30);
    [_button setImage:[UIImage imageNamed:@"iconfont-chazhaowodeweizhi.png"] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(dingwei) forControlEvents:UIControlEventTouchUpInside];
    [_mapView addSubview:_button];
}

//#pragma mark - CoreLocation 代理
//#pragma mark 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
////可以通过模拟器设置一个虚拟位置，否则在模拟器中无法调用此方法
//-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
//    CLLocation *location=[locations firstObject];//取出第一个位置
//    coordinate=location.coordinate;//位置坐标
//    NSLog(@"经度：%f,纬度：%f,海拔：%f,航向：%f,行走速度：%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
//    //如果不需要实时定位，使用完即使关闭定位服务
//    [_locationManager stopUpdatingLocation];
//    
//}

//#pragma mark - 地图控件代理方法
//#pragma mark 更新用户位置，只要用户改变则调用此方法（包括第一次定位到用户位置）
//-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
//    
//    NSLog(@"%@",userLocation);
//    //设置地图显示范围(如果不进行区域设置会自动显示区域范围并指定当前用户位置为地图中心点)
////        MKCoordinateSpan span=MKCoordinateSpanMake(0.01, 0.01);
////        MKCoordinateRegion region=MKCoordinateRegionMake(userLocation.location.coordinate, span);
////        [_mapView setRegion:region animated:true];
//}


#pragma mark 添加大头针 
-(void)addAnnotation{
    CLLocationCoordinate2D location1=CLLocationCoordinate2DMake(38.87682, 121.5473);
    KCAnnotation *annotation1=[[KCAnnotation alloc]init];
    annotation1.title=@"GY";
    //annotation1.subtitle=@"Kenshin Cui's Studios";
    annotation1.coordinate=location1;
    annotation1.image=[UIImage imageNamed:@"icon_openmap_item@2x.png"];
    annotation1.icon=[UIImage imageNamed:@"icon_paopao_waterdrop_streetscape@2x.png"];
//    //view自定义的详情
//    annotation1.detail=@"HE";
//    //星级的图片
//    annotation1.rate=[UIImage imageNamed:@"icon_Movie_Star_rating.png"];
    [_mapView addAnnotation:annotation1];
    
}

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    //由于当前位置的标注也是一个大头针，所以此时需要判断，此代理方法返回nil使用默认大头针视图
    if ([annotation isKindOfClass:[KCAnnotation class]]) {
//        static NSString *key1=@"AnnotationKey1";
//        MKAnnotationView *annotationView=[_mapView dequeueReusableAnnotationViewWithIdentifier:key1];
//        //如果缓存池中不存在则新建
//        if (!annotationView) {
        MKAnnotationView *annotationView=[[MKAnnotationView alloc]init];
        annotationView.canShowCallout=true;//允许交互点击
        annotationView.calloutOffset=CGPointMake(0, 1);//定义详情视图偏移量
        annotationView.selected=YES;
        annotationView.leftCalloutAccessoryView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_paopao_waterdrop_streetscape@2x.png"]];//定义详情左侧视图
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:@"iconfont-daohang-4.png"] forState:UIControlStateNormal];
        [button setTitle:@"导航" forState:UIControlStateNormal];
        button.frame = CGRectMake(0, 0, 75, 30);
        button.backgroundColor=[UIColor colorWithRed:147/255.0 green:155/255.0 blue:255/255.0 alpha:1];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UIView *rightView = [[UIView alloc] init];
        rightView.frame = CGRectMake(0, 0, 75, 30);
        [rightView addSubview:button];

        annotationView.rightCalloutAccessoryView = rightView;
        
//        }
        
        //修改大头针视图
        //重新设置此类大头针视图的大头针模型(因为有可能是从缓存池中取出来的，位置是放到缓存池时的位置)
        //annotationView.annotation=annotation;
        annotationView.image=((KCAnnotation *)annotation).image;//设置大头针视图的图片
        
        return annotationView;
    }
//    else if([annotation isKindOfClass:[KCCalloutAnnotation class]]){
//        //对于作为弹出详情视图的自定义大头针视图无弹出交互功能（canShowCallout=false，这是默认值），在其中可以自由添加其他视图（因为它本身继承于UIView）
//        KCCalloutAnnotationView *calloutView=[KCCalloutAnnotationView calloutViewWithMapView:mapView];
//        calloutView.annotation=annotation;
//        calloutView.canShowCallout=true;
//        calloutView.calloutOffset=CGPointMake(0, 1);
//        return calloutView;
//    }
    else {
        return nil;
    }
}

-(void)buttonClick:(UIButton *)button{
    NSLog(@"导航");
    
    self.geocoder=[[CLGeocoder alloc]init];
    //这个方法只能生效1个，所以不能分开写
    [self.geocoder geocodeAddressString:@"大连华臣影城西安路店" completionHandler:^(NSArray *placemarks, NSError *error) {
        if (error) return;
        CLPlacemark *fromPm=[placemarks firstObject];
        [self.geocoder geocodeAddressString:@"大连华臣影城黑石礁店" completionHandler:^(NSArray *placemarks, NSError *error) {
            CLPlacemark *toPm=[placemarks firstObject];
            
            //设置方向请求
            MKDirectionsRequest *request=[[MKDirectionsRequest alloc]init];
            //设置起点终点
            MKPlacemark *sourcePm=[[MKPlacemark alloc] initWithPlacemark:fromPm];
            request.source=[[MKMapItem alloc] initWithPlacemark:sourcePm];
            MKPlacemark *destiPm=[[MKPlacemark alloc] initWithPlacemark:toPm];
            request.destination=[[MKMapItem alloc]initWithPlacemark:destiPm];
            //request.transportType = MKDirectionsTransportTypeAutomobile ;
            //定义方向对象
            MKDirections *dirs=[[MKDirections alloc]initWithRequest:request];
            //计算路线
            [dirs calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
                NSLog(@"总共有%lu条线路",(unsigned long)response.routes.count);
                MKRoute *str= response.routes[0];
//                response.routes.MKDirectionsTransportType=MKDirectionsTransportTypeAutomobile;
                NSLog(@"name=%@,distance=%f,expectedTravelTime=%f",str.name,str.distance,str.expectedTravelTime);
                for (MKRoute *route in response.routes) {
                    //MKPolyline代表地图上路径。画在MKMapView上
                    for (MKRouteStep *step in route.steps) {
                        [_mapView addOverlay:step.polyline];
                        NSLog(@"instructions=%@,distance=%f",step.instructions,step.distance);
                    }
                    //[_mapView addOverlay:route.polyline];
                }
            }];
        }];
    }];
}
//划线就是添加路径，就是添加遮盖
-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id<MKOverlay>)overlay{
    MKPolylineRenderer *renderer=[[MKPolylineRenderer alloc]initWithOverlay:overlay];
    renderer.strokeColor=[UIColor redColor];
    
    return renderer;
}
-(void)dingwei{
    [_mapView setCenterCoordinate:_mapView.userLocation.location.coordinate animated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.hidesBottomBarWhenPushed=YES;
}
-(void)viewDidAppear:(BOOL)animated{
    self.navigationController.hidesBottomBarWhenPushed=NO;
}
//#pragma mark 选中大头针时触发
////点击一般的大头针KCAnnotation时添加一个大头针作为所点大头针的弹出详情视图
//-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
//    KCAnnotation *annotation=view.annotation;
//    if ([view.annotation isKindOfClass:[KCAnnotation class]]) {
//        //点击一个大头针时移除其他弹出详情视图
////        [self removeCustomAnnotation];
//        //添加详情大头针，渲染此大头针视图时将此模型对象赋值给自定义大头针视图完成自动布局
//        KCCalloutAnnotation *annotation1=[[KCCalloutAnnotation alloc]init];
//        annotation1.icon=annotation.icon;
//        annotation1.detail=annotation.detail;
//        annotation1.rate=annotation.rate;
//        annotation1.coordinate=view.annotation.coordinate;
//        [mapView addAnnotation:annotation1];
//    }
//}
//
//#pragma mark 取消选中时触发
//-(void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view{
//    [self removeCustomAnnotation];
//}
//
//#pragma mark 移除所用自定义大头针
//-(void)removeCustomAnnotation{
//    [_mapView.annotations enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//        if ([obj isKindOfClass:[KCCalloutAnnotation class]]) {
//            [_mapView removeAnnotation:obj];
//            [self addAnnotation];
//        }
//    }];
//}


//CLLocation：用于表示位置信息，包含地理坐标、海拔等信息，包含在CoreLoaction框架中。
//
//MKUserLocation：一个特殊的大头针，表示用户当前位置。
//
//CLPlacemark：定位框架中地标类，封装了详细的地理信息。
//
//MKPlacemark：类似于CLPlacemark，只是它在MapKit框架中，可以根据CLPlacemark创建MKPlacemark。

//MKPinAnnotationView
//设置第一次出现从天而降
//annoView.animatesDrop=YES;

//    MKMapItem *from=[[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc] initWithPlacemark:fromPm]];
//    MKMapItem *to=[[MKMapItem alloc]initWithPlacemark:[[MKPlacemark alloc] initWithPlacemark:toPm]];
//    NSMutableDictionary *options=[NSMutableDictionary dictionary];
//    options[MKLaunchOptionsDirectionsModeKey]=MKLaunchOptionsDirectionsModeDriving;
//    options[MKLaunchOptionsShowsTrafficKey]=@YES;
//    [MKMapItem openMapsWithItems:@[from,to] launchOptions:options];

@end
